<?php 

$host = '127.0.0.1';
$port = 3306;
$user = 'root';
$password = 'qaz123';
$dbname = 'test';

//mysqli
$conn = mysqli_connect($host, $user, $password, $dbname, $port);

//设置字符编码
mysqli_set_charset($conn, 'utf8mb4');


// //避免sql注入攻击
// $sql = 'insert into `post` (title, content, created_at) values (?, ?, ?)';
// //构建预处理sql 语句
// $stmt = mysqli_prepare($conn, $sql);
//绑定参数
// $title = '这是一篇测试文章';
// $content = '测试sql防止注入';
// $created_at = '2020-05-27';
// mysqli_stmt_bind_param($stmt, 'sss', $title, $content, $created_at);
// //执行 Sql 语句
// mysqli_stmt_execute($stmt);
// //打印影响行数
// printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));
// //获取插入记录对应的主键ID
// $lastInsertId = mysqli_stmt_insert_id($stmt);

// //释放资源
// mysqli_stmt_close($stmt);



//通过连接实例上进行查询
$sql = 'select * from `post` where id = 1';
$res = mysqli_query($conn, $sql);


// //查询新插入的记录
// $sql = 'select * from `post` where id = ' . $lastInsertId;
// $res = mysqli_query($conn, mysqli_escape_string($conn, $sql));
// $post = mysqli_fetch_object($res, Post::class);
// echo $post;



// var_dump($res);

//获得所有结果
// $rows = mysqli_fetch_all($res, MYSQLI_ASSOC);
// $post = mysqli_fetch_object($res, Post::class);
// echo $post;

$rows = mysqli_fetch_assoc($res);
echo '<pre>';
var_dump($rows);
//释放缓存
// mysqli_free_result($res);



class Post 
{
    public $id;
    public $title;
    public $content;
    public $create_at;

    public function __toString()
    {
        return '[#' . $this->id .']' . $this->title . ':' . $this->content;
    }
}
//将数据库返回结果映射到指定个对象




//关闭连接
mysqli_close($conn);